<template>
  <div class="login">
    <el-card shadow="hover">
      <div class="login-title"></div>
      <el-form ref="form" :model="userInfo" :rules="rules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="userInfo.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <!-- 密码框 -->
        <el-form-item prop="password">
          <el-input
            v-model="userInfo.password"
            type="password"
            show-password
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 注册 -->
      <el-link :underline="false" @click="$router.push('/reg')">还没有账号,去注册</el-link>
    </el-card>
  </div>
</template>
<script>
import { loginAPI } from '@/APl/user.js'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // { min: 1, max: 10, message: '长度在 1 到 10 位数字字母', trigger: 'blur' }
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名长度为1-10位字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度为6-15位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await loginAPI(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.commit('user/updateToken', res.token)
          this.$router.push('/')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login {
  height: 100%;
  background: url(../assets/images/login_bg.jpg) no-repeat;
  background-size: cover;
  .el-card {
    // height: 355px;
    width: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .login-title {
      height: 60px;
      background: url(../assets/images/login_title.png) 50% no-repeat;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>
